#include "awx_udp.h"
#include "ui_awx_udp.h"
#include <QMetaEnum>
#include <QScrollBar>
#include <QStatusBar>
#include <QDialog>
#include <QSettings>
#include <QFile>

AWX_UDP::AWX_UDP(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AWX_UDP),
    socket(new QUdpSocket(this))
{
    this->socket->setObjectName("socket");
    ui->setupUi(this);
    //设备对话框图标及标题
    //    this->setWindowIcon(QIcon(":/setting"));
    //    this->setWindowTitle(QString("网络参数设置"));
    //初始化ComboBox_local_ip的本地所有IP地址
    foreach (QHostAddress ip, QNetworkInterface::allAddresses()) {
        if(ip.protocol() == QAbstractSocket::IPv4Protocol) //只添加IPv4的地址
        {
            ui->comboBox_local_ip->addItem(ip.toString());
        }
    }
    //给textEdit添加右键清屏菜单
    QAction *action_clear = new QAction("清屏",ui->textEdit);
    QAction *action_info = new QAction("网口状态信息",ui->textEdit);
    ui->textEdit->addAction(action_clear);
    ui->textEdit->addAction(action_info);
    connect(action_clear,&QAction::triggered,ui->textEdit,&QTextEdit::clear);
    connect(action_info,&QAction::triggered,this,&AWX_UDP::show_socket_infomation);
    ui->textEdit->setContextMenuPolicy(Qt::ActionsContextMenu);
    //socket状态改变处理
    //    connect(socket,&QUdpSocket::stateChanged,this,&AWX_UDP::socket_stateChanged);
    //显示socket初始状态信息
    show_socket_infomation();
    //    connect(socket,&QUdpSocket::error,this,&AWX_UDP::socket_error);
    //    connect(socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(socket_error(QAbstractSocket::SocketError)));
    read_config();
}

AWX_UDP::~AWX_UDP()
{
    delete ui;
}

void AWX_UDP::on_lineEdit_remote_ip_editingFinished()
{
    QHostAddress ip(ui->lineEdit_remote_ip->text());
    if(ip.isNull())
    {
        ui->textEdit->append(QString("输入的分机IP地址\"%1\"格式有误，请更正！").arg(ui->lineEdit_remote_ip->text()));
        ui->pushButton_connect->setEnabled(false);
        ui->lineEdit_remote_ip->selectAll();
        ui->lineEdit_remote_ip->setFocus();
    }else{
        ui->pushButton_connect->setEnabled(true);
    }
}

void AWX_UDP::on_pushButton_connect_clicked()
{
    if(socket->state() != QAbstractSocket::ConnectedState){
        if(ui->checkBox_bind->isChecked())
        {
            if(QHostAddress(ui->comboBox_local_ip->currentText()).isNull())
            {
                socket->bind(quint16(ui->spinBox_local_port->value()));
            }else {
                socket->bind(QHostAddress(ui->comboBox_local_ip->currentText()),quint16(ui->spinBox_local_port->value()));
            }
        }
        socket->connectToHost(QHostAddress(ui->lineEdit_remote_ip->text()),quint16(ui->spinBox_remote_port->value()));
    }else{
        socket->disconnectFromHost();
    }
}

void AWX_UDP::on_socket_stateChanged(QAbstractSocket::SocketState state)
{
    //    ui->statusBar->findChild<QLabel*>("statusLable")->setText(
    ui->statusLabel->setText(
                QString(
                    "<html><head/><body><p>网络接口错误信息：<span style=\" color:#ff0000;\">%1</span></p></body></html>"
                    ).arg("None").replace("color:#ff0000","color:#0000ff"));
    QMetaEnum me = QMetaEnum::fromType<QAbstractSocket::SocketState>();
    ui->textEdit->append(QString("网络状态：%1").arg(me.key(state)));
    ui->textEdit->append(QString("本地IP地址：%1 本地端口号：%2").arg(socket->localAddress().toString()).arg(socket->localPort()));
    ui->textEdit->append(QString("分机IP地址：%1 分机端口号：%2").arg(socket->peerAddress().toString()).arg(socket->peerPort()));
    //更新Ui控件状态
    if(state == QAbstractSocket::ConnectedState)
    {
        ui->pushButton_connect->setText("断开连接");
        ui->pushButton_connect->setIcon(QIcon(":/led_green"));
        ui->checkBox_bind->setEnabled(false);
        ui->comboBox_local_ip->setEnabled(false);
        ui->spinBox_local_port->setEnabled(false);
        ui->lineEdit_remote_ip->setEnabled(false);
        ui->spinBox_remote_port->setEnabled(false);
    }else{
        ui->pushButton_connect->setText("连接分机");
        ui->pushButton_connect->setIcon(QIcon(":/led_red"));
        ui->checkBox_bind->setEnabled(true);
        if(ui->checkBox_bind->isChecked())
        {
            ui->comboBox_local_ip->setEnabled(true);
            ui->spinBox_local_port->setEnabled(true);
        }
        ui->lineEdit_remote_ip->setEnabled(true);
        ui->spinBox_remote_port->setEnabled(true);
    }
    //TextEdit始终显示最后新信息
    ui->textEdit->verticalScrollBar()->setSliderPosition(ui->textEdit->verticalScrollBar()->maximum());
}

void AWX_UDP::show_socket_infomation()
{
    on_socket_stateChanged(socket->state());
    ui->textEdit->verticalScrollBar()->setSliderPosition(ui->textEdit->verticalScrollBar()->maximum());
}

void AWX_UDP::on_socket_error(QAbstractSocket::SocketError socketError)
{
    socketError = socketError;
    ui->statusLabel->setText(
                QString(
                    "<html><head/><body><p>网络接口错误信息：<span style=\" color:#ff0000;\">%1</span></p></body></html>"
                    ).arg(socket->errorString()));
    this->vaild = false;
    //网络错误处理待完善,当出错后不能直接再重新邦定或连接新地址：。
}

void AWX_UDP::on_comboBox_local_ip_currentIndexChanged(const QString &arg1)
{
    if(ui->comboBox_local_ip->currentIndex() != 0){
        ui->lineEdit_remote_ip->setText(arg1);
    }
}

void AWX_UDP::show()
{
    //    QDialog dlg ;
    //    dlg.setWindowTitle(this->windowTitle());
    //    dlg.setWindowIcon(this->windowIcon());
    //    QLayout *awx_udp_layout = this->layout();
    //    dlg.setLayout(awx_udp_layout);
    //    dlg.exec();
    //    this->setLayout(awx_udp_layout);
    this->setWindowFlag(Qt::Dialog);
    this->setWindowModality(Qt::ApplicationModal);
    QWidget::show();
}

void AWX_UDP::read_config()
{
    QFile file("./cfg.ini");
    if(file.exists()){
        QSettings cfg("./cfg.ini",QSettings::IniFormat);
        cfg.beginGroup("udp");
        ui->spinBox_local_port->setValue(cfg.value("local_port").toInt());
        ui->lineEdit_remote_ip->setText(cfg.value("remote_ip").toString());
        ui->spinBox_remote_port->setValue(cfg.value("remote_port").toInt());
        cfg.endGroup();
    }else {
        qDebug()<<"./cfg.ini is not exists";
    }
}

void AWX_UDP::write_config()
{
    QSettings cfg("./cfg.ini",QSettings::IniFormat);
    cfg.beginGroup("udp");
    cfg.setValue("local_port",ui->spinBox_local_port->value());
    cfg.setValue("remote_ip",ui->lineEdit_remote_ip->text());
    cfg.setValue("remote_port",ui->spinBox_remote_port->value());
    cfg.endGroup();
}

void AWX_UDP::on_socket_connected()
{
    write_config();
    this->vaild = true;
    emit toggle(true);
}

void AWX_UDP::on_socket_disconnected()
{
    this->vaild = false;
    emit toggle(false);
}

bool AWX_UDP::isVaild()
{
    return this->vaild;
}

void AWX_UDP::on_socket_readyRead()
{
    emit readyRead();
}

QNetworkDatagram AWX_UDP::receiveDatagram(qint64 maxSize)
{
    return socket->receiveDatagram(maxSize);
}
